package com.hktry.ioc;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 *
 * @version 1.0
 * @author hktry
 * @Email 13117011726@163.com Descriptions： SimpleBeanFactory.java Company：
 *        浙江祥生物业服务有限公司
 * @date 2017年3月6日
 */
public class SimpleBeanFactory implements BeanFactory {

	private Object obj;

	private final Class cls;

	public SimpleBeanFactory(Class cls) {
		// TODO Auto-generated constructor stub
		this.cls = cls;
		try {
			this.obj = cls.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Object getBean() {
		// TODO Auto-generated method stub
		return obj;
	}

	@Override
	public void setProperties(Map map) {
		// TODO Auto-generated method stub
		PropertyDescriptor[] props=null;
		try {
			props=Introspector.getBeanInfo(cls,Object.class).getPropertyDescriptors();
			if (props != null) {
				 for (int i = 0; i < props.length; i++) {
					 Method m=props[i].getWriteMethod();
					 Autowired a=m.getAnnotation(Autowired.class);
					 if(a!=null){
						 //将直接的值传过去
						 m.invoke(obj, map.get(a.value()));
					 }
				 }
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
